http = require("http")
koa = require("koa")
co = require('co')
koaBody = require("koa-body")
Jade = require("koa-jade")
Config = require("./config")

router = require("./router").getRouter()

enableDestory = require("server-destroy")
Promise = require("bluebird")

app = koa()

jade = new Jade({
    viewPath: Config.viewPath
})

app.use(jade.middleware)

app.use koaBody(multipart: true, formidable: {uploadDir: Config.uploadDir, keepExtensions: true})
app.use(router.routes()).use(router.allowedMethods())


server = http.createServer(app.callback())
exports.server = server
server.on 'error', (err)->
    console.log(err)
enableDestory server

port = Config.port
exports.start = ->
    # get weixin token
    yield from require("./utils/weixin-token").gGetToken()

    yield Promise.promisify(server.listen.bind(server))(port)

    console.log("server started on " + port)

co(exports.start()).catch (err)->
    console.log(err)